from django import forms

from .models import Book


class AuthorForm(forms.ModelForm):

    books = forms.ModelMultipleChoiceField(
        Book.objects.all(),
        required=False,
    )

    def __init__(self, *args, **kwargs):
        print('__init__ called')
        super(AuthorForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            print('='*20)
            print(self.instance.pk)
            self.initial['books'] = self.instance.books.values_list(
                'pk', flat=True)

    def save(self, *args, **kwargs):
        print('save called')
        instance = super(AuthorForm, self).save(*args, **kwargs)
        if instance.pk is None:
            instance.save()
        if instance.pk:
            print('save')
            print(self.cleaned_data['books'])
            print(instance.books.all())
            for book in instance.books.all():
                if book not in self.cleaned_data['books']:
                    instance.books.remove(book)
            for book in self.cleaned_data['books']:
                if book not in instance.books.all():
                    instance.books.add(book)
        return instance
